package org.ouwh.oowiki;

import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.ouwh.fw.model.data.Struct;
import org.ouwh.fw.model.service.Service;
import org.ouwh.fw.util.MyProperties;

public class Log4jService extends Service {
	private static Log log = LogFactory.getLog(Log4jService.class);
	private volatile Properties configs;

	@Override
	protected void dumpToStruct(Struct struct) {
		FileInputStream in = null;
		try {
			MyProperties myProps = new MyProperties(configs);
			in = new FileInputStream(getConfigPath());
			myProps.loadKeys(in);
			Iterator<String> it = myProps.getOrderedKeys();
			while (it.hasNext()) {
				String key = it.next();
				String value = myProps.getProperty(key);
				if (!key.equals("type")) {
					struct.addData(key, value);
				}
			}
		} catch (Exception e) {
			log.error("Get log4j config order failed.", e);
		} finally {
			try {
				in.close();
			} catch (Exception e) {
			}
		}
	}

	@Override
	protected void init(Properties properties) {
		// Log4j has been init in ModelCore, here do nothing
		this.configs = properties;
	}

	@Override
	protected void reset(Properties properties) throws Exception {
		this.configs = properties;
		LogManager.resetConfiguration();
		PropertyConfigurator.configure(properties);
		log.info("Log4j service resetted.");
	}

	@Override
	protected void shutdown() throws Exception {
		log.info("Log4j service stopped.");
	}

	@Override
	protected void startup() throws Exception {
		log.info("Log4j service started.");
	}

}
